package assignmentImplementation;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

import keyValueBaseInterfaces.MemoryMappedFile;
import keyValueBaseInterfaces.Store;

public class StoreImpl implements Store
{

	private boolean initialized;
	private MemoryMappedFile mmf;
	private RandomAccessFile raf;
	
	public StoreImpl(String storeFilename) throws FileNotFoundException {

		this.initialized = false;
		File file = new File(storeFilename);
		
		if(!file.isFile() && file.canRead() && file.canWrite()){
			throw new FileNotFoundException();
		}
		else{
			raf = new RandomAccessFile(file, "rw");

				try {
					long buffer =  raf.length() + Long.parseLong("209715200"); // 200MB
					raf.setLength(buffer);
					FileChannel fc= raf.getChannel();
					mmf = new MemoryMappedFile(fc, FileChannel.MapMode.READ_WRITE, 0, buffer);
					this.initialized = true;
				}catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

	
	public byte[] read(Long position, int length) {
		byte[] dst = new byte[length];
		mmf.get(dst, position);
		return dst;
	}

	public void write(Long position, byte[] value) {
		mmf.put(value, position);
		
	}
	
	public boolean isInitialized(){
		return this.initialized;
	}
	
}
